﻿using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Director
{
	static class MarshalUtf8
	{
		private static readonly UTF8Encoding _utf8;

		static MarshalUtf8()
		{
			_utf8 = new UTF8Encoding();
		}

		public static IntPtr StringToHGlobalUtf8(String data)
		{
			var dataEncoded = _utf8.GetBytes(data + "\0");
			var size = Marshal.SizeOf(dataEncoded[0]) * dataEncoded.Length;
			var pData = Marshal.AllocHGlobal(size);
			Marshal.Copy(dataEncoded, 0, pData, dataEncoded.Length);
			return pData;
		}

		public static String PtrToStringUtf8(IntPtr pData)
		{
			// this is just to get buffer length in bytes
			var errStr = Marshal.PtrToStringAnsi(pData);
			var length = errStr.Length;

			var data = new byte[length];
			Marshal.Copy(pData, data, 0, length);

			return _utf8.GetString(data);
		}
	}
}